package com.xbongbong.paas.help;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasAttachmentEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.model.StageProcessModel;
import com.xbongbong.paas.pojo.AttrValuePojo;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.redis.RedisTimeConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.enums.PaasStageEnum;
import com.xbongbong.pro.enums.errorcodes.ImportErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.RelativeProductEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.help.SaveFormatHelp;
import com.xbongbong.saas.model.ProductCategoryModel;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 吴峰
 * @version v1.0
 * @date 2019/5/23 21:58
 * @since v1.0
 */
@Component
public class ProSaveHelp {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProSaveHelp.class);

    private static final String ID = "id";

    private static final String NAME = "name";

    private static ProSaveHelp proSaveHelp;

    @Resource
    private StageProcessModel stageProcessModel;
    @Resource
    private ProductCategoryModel productCategoryModel;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private PaasRedisHelper paasRedisHelper;


    @PostConstruct
    public void init(){
        proSaveHelp = this;
        proSaveHelp.stageProcessModel = this.stageProcessModel;
        proSaveHelp.productCategoryModel = this.productCategoryModel;
        proSaveHelp.productCategoryModel = this.productCategoryModel;
        proSaveHelp.paasRedisHelper = this.paasRedisHelper;
    }

    /**
     * 获取id等想要的数据
     * 关联数据：{"dataId": 关联数据id} ，只有获取这个dataId即可
     * 关联数据多选：[{"dataId": 关联数据id}] ，只要获取这个dataId数组即可
     * 用户单选：{"id": "" , "name": ""}，只需要id即可
     * 部门单选、所属部门：{"id": 1 , "name": ""}，只需要id即可
     * 用户多选、协同人、负责人：[{"id": "1" , "name": ""}, {"id": "2", "name": ""}] 获取id列表即可 ["1", "2"]
     * 部门多选：[{"id": 1 , "name": ""}, {"id": 2, "name": ""}] 获取id列表即可 [1, 2]
     * 下拉框、单选按钮：{"value": "", "text": "选项值1"} ，只需要value即可
     * 附件：
     * @param validateDataDTO
     */
    public static void analyticalData(ValidateDataDTO validateDataDTO) throws XbbException {
        try {
            Map<String, FieldAttrEntity> explainMap = validateDataDTO.getExplainMap();
            JSONObject data = validateDataDTO.getData();
            // 字段删除时，流程需要移除数据
            if (!Objects.isNull(data)) {
                data.keySet().removeIf(key -> !explainMap.containsKey(key)
                        && !Objects.equals(key,"subId")
                        && !Objects.equals(key,BusinessConstant.PRODUCT_SUB_ID)
                        && !Objects.equals(key,BusinessConstant.REF_PRODUCT_ID)
                        && !Objects.equals(key, RelativeProductEnum.UNIT_NUM.getSaasAttr())
                        && !Objects.equals(key, ProductConstant.SEQ)
                        && !Objects.equals(key, ProductEnum.ENABLE_BATCH_SHELF_LIFE.getSaasAttr())
                        && !Objects.equals(key, ProductEnum.ENABLE_SERIAL_NUMBER.getSaasAttr())
                        && !Objects.equals(key, ProductEnum.SHELF_LIFE_DAYS.getSaasAttr())
                        && !Objects.equals(key, ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr())
                        && !Objects.equals(key, BusinessConstant.SUB_DATA_ID)
                        && !Objects.equals(key, ProductConstant.PRICE)
                        && !Objects.equals(key, ProductConstant.UNIT_RATE)
                        && !Objects.equals(key, ProductConstant.TRANSFORM_UNIT_RATE)
                        && !Objects.equals(key, ProductConstant.UPDATE_COST)
                        && !Objects.equals(key, "clueId")
                        && !Objects.equals(key, "isBringCustomer")
                        && !Objects.equals(key,"contractId")
                        && !Objects.equals(key,"contractProductId")
                );
            }
            if (Objects.isNull(data)) {
                return;
            }
            Iterator<String> iterator = explainMap.keySet().iterator();
            while (iterator.hasNext()) {
                FieldAttrEntity fieldAttrEntity = explainMap.get(iterator.next());
                String attr = fieldAttrEntity.getAttr();
                Integer fieldType = fieldAttrEntity.getFieldType();
                if (Objects.equals(FieldTypeEnum.SEPARATOR.getType(), fieldType) || Objects.equals(FieldTypeEnum.MEMO.getType(), fieldType)) {
                    // 分割线、描述文本不录入数据
                    data.remove(attr);
                }else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA.getType())) {
                    if (Objects.isNull(data.get(attr))) {
                        data.put(attr, 0);
                    }
                    if (Objects.nonNull(data.get(attr)) && data.get(attr) instanceof Map) {
                        JSONObject linkData = data.getJSONObject(attr);
                        data.put(attr, linkData.getLong(FieldTypeEnum.DATAID.getAlias()));
                    }
                } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA_MULTI.getType())) {
                    if (Objects.nonNull(data.get(attr)) && data.get(attr) instanceof List) {
                        JSONArray linkDataArray = data.getJSONArray(attr);
                        if (CollectionsUtil.isNotEmpty(linkDataArray) && linkDataArray.get(0) instanceof Map) {
                            List<Long> lindDataIdList = new ArrayList<>();
                            for (int i = 0; i < linkDataArray.size(); i++) {
                                JSONObject linkData = linkDataArray.getJSONObject(i);
                                if (Objects.nonNull(linkData)) {
                                    lindDataIdList.add(linkData.getLong(FieldTypeEnum.DATAID.getAlias()));
                                }
                            }
                            data.put(attr, lindDataIdList);
                        }
                    }
                } else if (Objects.equals(fieldType, FieldTypeEnum.USER.getType())
                        || Objects.equals(fieldType, FieldTypeEnum.CREATORID.getType())) {
                    if (Objects.nonNull(data.get(attr)) && ((data.get(attr) instanceof Map || data.get(attr) instanceof ReturnUserAndDepartmentPojo))) {
                        JSONObject linkData = data.getJSONObject(attr);
                        if (Objects.nonNull(linkData)) {
                            // 处理合同无签订人导入
                            if (Objects.equals(linkData.getString(ID), StringConstant.NOT_IN_SYSTEM_ID)) {
                                JSONArray userArr = new JSONArray();
                                String nameLeaveMark = linkData.getString(NAME);
                                if ( StringUtil.isNotEmpty(nameLeaveMark) ) {
                                    linkData.put(NAME,nameLeaveMark.replaceAll(StringConstant.LEAVE_MARK,""));
                                }
                                userArr.add(linkData);
                                data.put(attr, userArr);
                                validateDataDTO.setNoSignImport(1);
                            } else {
                                data.put(attr, linkData.getString(ID));
                            }
                        }
                    }
                } else if (Objects.equals(fieldType, FieldTypeEnum.DEPT.getType())) {
                    if (Objects.nonNull(data.get(attr)) && ((data.get(attr) instanceof Map || data.get(attr) instanceof ReturnUserAndDepartmentPojo))) {
                        JSONObject linkData = data.getJSONObject(attr);
                        if (Objects.nonNull(linkData)) {
                            data.put(attr, linkData.get(ID));
                        }
                    }
                } else if (Objects.equals(fieldType, FieldTypeEnum.USER_GROUP.getType())
                        || Objects.equals(fieldType, FieldTypeEnum.DEPT_GROUP.getType())) {
                    if (Objects.nonNull(data.get(attr))) {
                        Boolean isList = data.getJSONArray(attr) != null;
                        JSONArray jsonArray = data.getJSONArray(attr);
                        if (isList) {
                            List<Object> list = getIdList(jsonArray);
                            if (!list.isEmpty()) {
                                data.put(attr, list);
                            }
                        }
                    }
                } else if (Objects.equals(fieldType, FieldTypeEnum.COMBO.getType())
                        || Objects.equals(fieldType, FieldTypeEnum.RADIO_GROUP.getType())) {
                    if (Objects.nonNull(data.get(attr)) && data.get(attr) instanceof Map) {
                        JSONObject linkData = data.getJSONObject(attr);
                        data.put(attr, linkData.get("value"));
                    }
                } else if (Objects.equals(fieldType, FieldTypeEnum.COMBO_CHECK.getType())
                        || Objects.equals(fieldType, FieldTypeEnum.CHECKBOX_GROUP.getType())) {
                    JSONArray jsonArray = data.getJSONArray(attr);
                    if (Objects.nonNull(jsonArray)) {
                        List<Object> list = getValueList(jsonArray);
                        if (!list.isEmpty()) {
                            data.put(attr, list);
                        }
                    }
                } else if (Objects.equals(fieldType, FieldTypeEnum.COUSERID.getType())) {
                    if (Objects.nonNull(data.get(attr))) {
                        Boolean isList = data.getJSONArray(attr) != null;
                        JSONArray jsonArray = data.getJSONArray(attr);
                        if (isList) {
                            List<ReturnUserAndDepartmentPojo> list = jsonArray.toJavaList(ReturnUserAndDepartmentPojo.class);
                            if (!list.isEmpty()) {
                                validateDataDTO.setCoUserId(list);
                                List<Object> idList = getIdList(jsonArray);
                                data.put(FieldTypeEnum.COUSERID.getAlias(), idList);
                            }
                        }
                    }
                } else if (Objects.equals(fieldType, FieldTypeEnum.OWNERID.getType())) {
                    if (Objects.nonNull(data.get(attr))) {
                        boolean isList = data.getJSONArray(attr) != null;
                        JSONArray jsonArray = data.getJSONArray(attr);
                        if (isList) {
                            List<ReturnUserAndDepartmentPojo> list = jsonArray.toJavaList(ReturnUserAndDepartmentPojo.class);
                            if (!list.isEmpty()) {
                                List<Object> idList = getIdList(jsonArray);
                                data.put(FieldTypeEnum.OWNERID.getAlias(), idList);
                            }
                        }
                    }
                } else if (Objects.equals(fieldType, FieldTypeEnum.DEPARTMENTID.getType())) {
                    // 所属部门
                    if (Objects.nonNull(data.get(attr)) && (data.get(attr) instanceof Map || data.get(attr) instanceof ReturnUserAndDepartmentPojo)) {
                        JSONObject linkData = data.getJSONObject(attr);
                        if (Objects.nonNull(linkData)) {
                            validateDataDTO.setDepartmentId(linkData.getLong(ID));
                        }
                    } else if (Objects.nonNull(data.get(attr)) && data.get(attr) instanceof Number) {
                        validateDataDTO.setDepartmentId(data.getLong(attr));
                    }
                    if (Objects.isNull(data.get(attr))) {
                        validateDataDTO.setDepartmentId(0L);
                    }
                } else if (Objects.equals(fieldType, FieldTypeEnum.SUB_FORM.getType())
                        || Objects.equals(fieldType, FieldTypeEnum.CONTACT_NUMBER.getType())
                        || Objects.equals(fieldType, FieldTypeEnum.SINGLE_SUB_FORM.getType())
                        || Objects.equals(fieldType, FieldTypeEnum.SWITCH_TEXT.getType())
                        || Objects.equals(fieldType,FieldTypeEnum.SELECT_PRODUCT.getType())) {
                    JSONArray jsonArray = data.getJSONArray(attr);
                    if (Objects.nonNull(jsonArray)) {
                        Iterator jsonIterator = jsonArray.iterator();
                        Map<String, FieldAttrEntity> subFieldMap = ExplainUtil.getExplainMapByList(fieldAttrEntity.getSubForm().getItems());
                        int i = 0;
                        while (jsonIterator.hasNext()) {
                            JSONObject jsonObject = (JSONObject) jsonIterator.next();
                            // 去掉没用的字段
                            jsonObject.remove(BusinessConstant.SUB_ID);
                            if(!Objects.equals(FieldTypeEnum.SELECT_PRODUCT.getType() , fieldType)) {
                                jsonObject.remove(ProductEnum.ENABLE_BATCH_SHELF_LIFE.getSaasAttr());
                                jsonObject.remove(ProductEnum.ENABLE_SERIAL_NUMBER.getSaasAttr());
                                jsonObject.remove(ProductEnum.SHELF_LIFE_DAYS.getSaasAttr());
                            }
                            ValidateDataDTO subValidateData = new ValidateDataDTO();
                            subValidateData.setData(jsonObject);
                            subValidateData.setExplainMap(subFieldMap);
                            subValidateData.setIsImport(validateDataDTO.getIsImport());
                            analyticalData(subValidateData);
                            jsonArray.set(i, subValidateData.getData());
                            i++;
                        }
                        data.put(attr, jsonArray);
                    }
                } else if (Objects.equals(fieldType, FieldTypeEnum.IMAGE.getType()) && StringUtil.isNotEmpty(data.getString(attr)) && Objects.equals(1, validateDataDTO.getIsImport())) {
                    String importString = data.getString(attr);
                    JSONArray fileArray = new JSONArray();
                    if (Objects.nonNull(importString)) {
                        String[] importArray = importString.split(";");
                        if (importArray.length > BasicConstant.NINE) {
                            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235068);
                        }
                        for (int i = 0; i < importArray.length; i++) {
                            String fileName = importArray[i];
                            // 图片名称校验一下后缀
                            boolean imageExtBool = isSupportFileType(fileName.split("\\.")[fileName.split("\\.").length - 1], "imageExtList");
                            if (!imageExtBool) {
                                throw new XbbException(ImportErrorCodeEnum.API_ERROR_235069);
                            }
                            fileArray.add(fileName.replace("\n", ""));
                        }
                    }
                    data.put(attr, fileArray);
                } else if (Objects.equals(fieldType, FieldTypeEnum.UPLOAD.getType()) && StringUtil.isNotEmpty(data.getString(attr)) && Objects.equals(1, validateDataDTO.getIsImport())) {
                    String importString = data.getString(attr);
                    JSONArray fileArray = new JSONArray();
                    if (Objects.nonNull(importString)) {
                        String[] importArray = importString.split(";");
                        if (importArray.length > BasicConstant.NINE) {
                            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235068);
                        }
                        try {
                            for (int i = 0; i < importArray.length; i++) {
                                String fileName = importArray[i].replace("\n", "");
                                String[] split = fileName.split("\\|");
                                // 附件名称不校验后缀了
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("attachIndex", split[1]);
                                jsonObject.put("ext", split[0].split("\\.")[1]);
                                jsonObject.put("filename", split[0]);
                                jsonObject.put("size", BasicConstant.ZERO);
                                fileArray.add(jsonObject);
                            }
                        } catch (Exception exception) {
                            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235070);
                        }
                    }
                    data.put(attr, JSON.toJSONString(fileArray));
                } else if (Objects.equals(fieldType, FieldTypeEnum.UPLOAD.getType())) {
                    //前端文件传object，es存放string,同时过滤掉前端的uid
                    JSONArray strArray = data.getJSONArray(attr);
                    if (Objects.nonNull(strArray)) {
                        List<PaasAttachmentEntityExt> cabinetFilePojoList = JSONArray.parseArray(strArray.toJSONString(), PaasAttachmentEntityExt.class);
                        if (Objects.nonNull(cabinetFilePojoList)) {
                            data.put(attr, JSON.toJSONString(cabinetFilePojoList));
                        }
                    }
                }else if (Objects.equals(fieldType, FieldTypeEnum.ACCOUNT_PERIOD.getType())) {
                    JSONObject jsonObject = data.getJSONObject(attr);
                    String receivablePeriodStr = Objects.isNull(jsonObject)? null : JSON.toJSONString(jsonObject);
                    data.put(attr,receivablePeriodStr);
                } else if (Objects.equals(fieldType, FieldTypeEnum.AREA.getType())) {
                    if (Objects.nonNull(data.get(attr)) && ((data.get(attr) instanceof Map || data.get(attr) instanceof ReturnUserAndDepartmentPojo))) {
                        JSONObject linkData = data.getJSONObject(attr);
                        if (Objects.nonNull(linkData)) {
                            data.put(attr, linkData.get(ID));
                        }
                    }
                } else if (Objects.equals(fieldType, FieldTypeEnum.PURCHASEABLE_GOODS.getType())) {
                    // instanceof List是为了过滤导入
                    if (Objects.nonNull(data.get(attr)) && (data.get(attr) instanceof List)) {
                        Boolean isList = data.getJSONArray(attr) != null;
                        JSONArray jsonArray = data.getJSONArray(attr);
                        if (isList) {
                            List<Object> list = getIdList(jsonArray);
                            if (!list.isEmpty()) {
                                data.put(attr, list);
                            }
                        }
                    }
                } else if (Objects.equals(fieldType, FieldTypeEnum.STAGE_THRUSTER.getType())) {
                    //解析阶段数据 导入的时候data格式是已经解析好的格式
                    if (Objects.nonNull(data.get(attr)) && data.get(attr) instanceof Map) {
                        JSONObject linkData = data.getJSONObject(attr);
                            handleStageData(linkData, data, attr, validateDataDTO.getCorpid(), validateDataDTO.getFormId());
                    }
                } else if (Objects.equals(fieldType, FieldTypeEnum.LABEL.getType())){
                    // TODO 将标签的解析放在这里，不再调用com.xbongbong.saas.help.SaasSaveHelp.dealLabelData，需要回测 @date 2022/1/6 14:38
                    JSONArray stringLableData = SaveFormatHelp.getStringLableData(data, attr);
                    data.put(attr, stringLableData);
                }
            }
            // 去掉多模板的模板选择字段
            data.remove(FieldTypeEnum.TEMPLATE.getAlias());
            removeDepartmentId(data);
        } catch (XbbException e) {
            LOGGER.error("proSaveHelp.analyticalData：",e);
            throw e;
        } catch (Exception e) {
            LOGGER.error("proSaveHelp.analyticalData：",e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100015);
        }
    }

    /**
     * 解析前端传来的阶段数据个数，将stageId, stageProcessId, stageRatio存入data中
     * @param linkData
     * @param data
     * @param attr
     */
    private static void handleStageData(JSONObject linkData, JSONObject data, String attr, String corpid, Long formId) {
            data.put(attr, linkData.get("value"));
            data.put(PaasStageEnum.STAGE_ID.getAttr(), linkData.get(PaasStageEnum.STAGE_ID.getSaasAttr()));
            data.put(PaasStageEnum.STAGE_PROCESS_ID.getAttr(), linkData.get(PaasStageEnum.STAGE_PROCESS_ID.getSaasAttr()));
            data.put(PaasStageEnum.STAGE_RATIO.getAttr(), linkData.get(PaasStageEnum.STAGE_RATIO.getSaasAttr()));
    }

    private static void removeDepartmentId(JSONObject data) {
        if (data.containsKey(FieldTypeEnum.DEPARTMENTID.getAlias())) {
            data.remove(FieldTypeEnum.DEPARTMENTID.getAlias());
        }
    }

    /**
     * 获取id列表
     * @param jsonArray
     * @return
     */
    public static List<Object> getValueList(JSONArray jsonArray) {
        List<Object> list = new ArrayList<>();
        if (Objects.nonNull(jsonArray)) {
            for(Object object: jsonArray) {
                if (object instanceof Map && Objects.nonNull(object) && Objects.nonNull(((JSONObject) object).get("value"))) {
                    JSONObject jsonObject = (JSONObject) object;
                    list.add(jsonObject.get("value"));
                }
            }
        }
        return list;
    }

    /**
     * 将fieldEditedList 转为 Map
     * @param avList
     * @return attr2ValueMap
     */
    public static Map<String,Object> attrValueList2Map(List<AttrValuePojo> avList){
        return avList.stream().collect(Collectors.toMap(AttrValuePojo::getAttr, AttrValuePojo::getValue, (a, b) -> b, () -> new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY)));
    }

    /**
     * 获取批量编辑的 data
     * @param avList
     * @return
     */
    public static JSONObject getBatchUpdateData(List<AttrValuePojo> avList) {
        JSONObject data = new JSONObject();
        for (AttrValuePojo attrValuePojo : avList) {
            data.put(attrValuePojo.getAttr(), attrValuePojo.getValue());
        }
        return data;
    }

    /**
     * 获取attrList
     * @param avList
     * @return
     */
    public static List<String> getAttrList(List<AttrValuePojo> avList) {
        return avList.stream().map(AttrValuePojo::getAttr).
                collect(Collectors.toCollection(() -> new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY)));
    }

    /**
     * 非字段依赖，获取单个AttrValuePojo
     * @param isFieldDependence
     * @param fieldEditedList
     * @return
     */
    public static AttrValuePojo getSingleAttrValuePojo(Boolean isFieldDependence, List<AttrValuePojo> fieldEditedList) throws XbbException {
        if (isFieldDependence) {
            return new AttrValuePojo("", "", "");
        }
        if (fieldEditedList.size() != 1 || Objects.isNull(fieldEditedList.get(0))) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, "非字段依赖时，获取singleAttrValuePojo失败");
        }
        return fieldEditedList.get(0);
    }

    /**
     * 获取id等想要的数据
     * @param dummyAttr2ValueMap
     * @param explainMap
     * @param corpid
     * @return
     */
    public static List<AttrValuePojo> analysisData(Map<String, Object> dummyAttr2ValueMap, Map<String, FieldAttrEntity> explainMap, String corpid) {
        List<AttrValuePojo> result = new ArrayList<>();

        for (Map.Entry<String, Object> av : dummyAttr2ValueMap.entrySet()) {
            String attr = av.getKey();
            Object value = av.getValue();
            FieldAttrEntity fieldAttrEntity = explainMap.get(attr);
            Integer fieldType = fieldAttrEntity.getFieldType();
            AttrValuePojo resItem = new AttrValuePojo();
            resItem.setAttr(attr);
            if (Objects.equals(fieldType, FieldTypeEnum.USER.getType())
                    || Objects.equals(fieldType, FieldTypeEnum.DEPT.getType())) {
                ReturnUserAndDepartmentPojo linkData = JSON.parseObject(JSON.toJSONString(value), ReturnUserAndDepartmentPojo.class);
                if (Objects.nonNull(linkData)) {
                    resItem.setValue(linkData.getName());
                }
            } else if (Objects.equals(fieldType, FieldTypeEnum.USER_GROUP.getType())
                    || Objects.equals(fieldType, FieldTypeEnum.DEPT_GROUP.getType())) {
                List<ReturnUserAndDepartmentPojo> jsonArray = JSONArray.parseArray(JSON.toJSONString(value), ReturnUserAndDepartmentPojo.class);
                if (Objects.nonNull(jsonArray)) {
                    List<String> list = new ArrayList<>();
                    jsonArray.forEach(item -> {
                        list.add(item.getName());
                    });
                    resItem.setValue(StringUtils.join(list, "、"));
                }
            } else if (Objects.equals(fieldType, FieldTypeEnum.COMBO.getType())
                    || Objects.equals(fieldType, FieldTypeEnum.RADIO_GROUP.getType())) {
                if (Objects.isNull(value)) {
                    resItem.setValue(value);
                } else if (value instanceof Map || value instanceof ItemPoJo) {
                    ItemPoJo itemPojo = JSONObject.parseObject(JSONObject.toJSONString(value), ItemPoJo.class);
                    if (Objects.isNull(itemPojo.getValue()) || Objects.equals("", itemPojo.getValue())) {
                        itemPojo.setValue(null);
                    }
                    ItemPoJo resValue = new ItemPoJo(itemPojo.getText(), itemPojo.getValue(), itemPojo.getChecked(), itemPojo.getColor());
                    resItem.setValue(Objects.isNull(itemPojo.getValue()) ? null : resValue);
                }
/*              原先数据结构
                if (value instanceof Map && Objects.nonNull(value)) {
                    JSONObject linkData = JSON.parseObject(JSON.toJSONString(value));
                    Object dummyValue = linkData.get("text");
                    if (Objects.isNull(dummyValue) || StringUtil.isEmpty(dummyValue.toString())) {
                        dummyValue = linkData.get("value");
                    }
                    resItem.setValue(dummyValue);
                }*/
            } else if (Objects.equals(fieldType, FieldTypeEnum.COMBO_CHECK.getType())
                    || Objects.equals(fieldType, FieldTypeEnum.CHECKBOX_GROUP.getType())) {
                if (Objects.isNull(value)) {
                    resItem.setValue(value);
                } else if (value instanceof JSONArray || value instanceof ArrayList ||value instanceof List) {
                    List<ItemPoJo> itemPojoList = JSON.parseArray(JSONArray.toJSONString(value), ItemPoJo.class);
                    List<ItemPoJo> valueList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    for (ItemPoJo item : itemPojoList) {
                        if (Objects.isNull(item.getValue()) || Objects.equals("", item.getValue())) {
                            continue;
                        }
                        ItemPoJo v = new ItemPoJo(item.getText(), item.getValue(), item.getChecked(), item.getColor());
                        valueList.add(v);
                    }
                    resItem.setValue(valueList.isEmpty() ? null : valueList);
                }
/*              原先数据结构
                JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(value));
                if (Objects.nonNull(jsonArray)) {
                    List<Object> list = new ArrayList<>();
                    jsonArray.forEach(item -> {
                        JSONObject jsonObject = (JSONObject) item;
                        list.add(jsonObject.get("text"));
                    });
                    resItem.setValue(StringUtils.join(list, "、"));

                }*/
            } else if (Objects.equals(fieldType, FieldTypeEnum.CATEGORY_ID.getType())) {
                Map<Long, String> categoryMap = proSaveHelp.productCategoryModel.categoryList(corpid);
                resItem.setValue(categoryMap.getOrDefault(Long.valueOf(value.toString()), ""));
            } else {
                resItem.setValue(value);
            }
            result.add(resItem);
        }
        return result;
    }

    /**
     * 获取id列表
     * @param jsonArray
     * @return
     */
    public static List<Object> getIdList(JSONArray jsonArray) {
        List<Object> list = new ArrayList<>();
        if (Objects.nonNull(jsonArray)) {
            for(Object object: jsonArray) {
                if (object instanceof JSONObject) {
                    JSONObject jsonObject = (JSONObject) object;
                    if (Objects.nonNull(jsonObject.get(ID))) {
                        list.add(jsonObject.get(ID));
                    }
                } else {
                    list.add(object);
                }
            }
        }
        return list;
    }

    public static Object getId(JSONObject jsonObject) {
        Object result = null;
        if (Objects.nonNull(jsonObject)) {
            result = jsonObject.get(ID);
        }
        return result;
    }

    /**
     * 快速编辑和批量编辑数据解析
     * @param value
     * @return
     */
    public static Object getValue(Object value, String attr, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        FieldAttrEntity fieldAttrEntity = explainMap.get(attr);
        if (Objects.isNull(fieldAttrEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.THIS_EXPLAIN_NOT_EXIST);
        }
        Integer fieldType = fieldAttrEntity.getFieldType();
        FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(fieldType);
        switch (fieldTypeEnum) {
            case TEXT:
            case TEXTAREA:
                value = value == null ? "" : value;
                break;
            case COMBO:
            case RADIO_GROUP:
                // 兼容下拉框单选，单选按钮的格式
                value = Objects.isNull(value) ? "" : value;
                if (value instanceof Map || value instanceof ItemPoJo) {
                    ItemPoJo valuePojo = JSONObject.parseObject(JSONObject.toJSONString(value), ItemPoJo.class);
                    if (Objects.isNull(valuePojo.getValue()) || Objects.equals(valuePojo.getValue(), "")) {
                        // 处理其他项 值为空的情况
                        value = "";
                    } else {
                        value = valuePojo.getValue();
                    }
                }
                break;
/*              原先数据结构
                if (value instanceof Map ) {
                    Map<String, Object> valueMap = (Map) value;
                    return valueMap.get("value");
                }*/
            case COMBO_CHECK:
            case CHECKBOX_GROUP:
                // 兼容下拉框复选，复选按钮的格式
                if (value instanceof JSONArray || value instanceof ArrayList || value instanceof List) {
                    List<ItemPoJo> itemPojoList = JSON.parseArray(JSONArray.toJSONString(value), ItemPoJo.class);
                    List<Object> list = itemPojoList.stream().map(ItemPoJo::getValue)
                            .filter(itemPoJoValue -> !Objects.isNull(itemPoJoValue) && !Objects.equals(itemPoJoValue, ""))
                            .collect(Collectors.toList());
                    value = list;
                }
/*                  原先数据结构
                    List<Map<String, Object>> valueList = (List) value;
                    List<Object> list = new ArrayList<>();
                    valueList.forEach(item->{
                        list.add(item.get("value"));
                    });
                    return list;*/
                break;
            case ACCOUNT_PERIOD:
                //代表是应收账期
                value = JSONObject.toJSONString(value);
                break;
            case USER:
                // 成员单选字段
                if (value != null){
                    JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(value));
                    value = jsonObject.getString(BusinessConstant.ID);
                }
                break;
            default:
                break;
        }

        return value;
    }


    /**
     * @Description: 判断传入的ext扩展名是否支持
     * @param ext
     * @param fileType
     * @Author cml
     * @CreateTime 2023/3/15 11:06
     */
    private static boolean isSupportFileType(String ext, String fileType) {
        Set value4Set = proSaveHelp.paasRedisHelper.getValue4Set(RedisPrefixConstant.MIGRATION_FILE_SUFFIX_LIST, fileType);
        if (Objects.nonNull(value4Set)) {
            return value4Set.contains(ext);
        }
        Set<String> set = new HashSet<>();
        CompanyConfigEntity companyConfigEntity = proSaveHelp.companyConfigModel.getByConfigAlias(CompanyConfigEnum.MIGRATION_FILE_SUFFIX_LIST.getAlias(), StringConstant.DEFAULT_CORPID);
        if (Objects.nonNull(companyConfigEntity)) {
            JSONObject jsonObject = JSONObject.parseObject(companyConfigEntity.getConfigValue());
            JSONArray exportWhiteCorpidList = jsonObject.getJSONArray(fileType);
            if (CollectionsUtil.isNotEmpty(exportWhiteCorpidList)) {
                set = new HashSet<>(exportWhiteCorpidList.toJavaList(String.class));
            }
        }
        proSaveHelp.paasRedisHelper.setValue4Set(RedisPrefixConstant.MIGRATION_FILE_SUFFIX_LIST, fileType, set, RedisTimeConstant.HUGE_DURATION);
        return set.contains(ext);
    }
}
